import express from "express";
import cors from "cors";
import dotenv from "dotenv";
import path from "path";
import { fileURLToPath } from "url";
import { connectDB } from "./config/database.js";

// 导入路由
import authRoutes from "./routes/auth.js";
import customerRoutes from "./routes/customers.js";
import shopRoutes from "./routes/shops.js";
import networkRoutes from "./routes/networks.js";
import waybillRechargeRoutes from "./routes/waybill-recharge.js";
import transactionRoutes from "./routes/transactions.js";
import uploadRoutes from "./routes/upload.js";
import waybillStatsRoutes from "./routes/waybill-stats.js";

// 获取当前文件路径
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

// 加载环境变量
dotenv.config();

const app = express();
const PORT = process.env.PORT || 3000;

// 中间件
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// 静态文件服务
app.use("/uploads", express.static(path.join(__dirname, "uploads")));

// 路由
app.use("/api/auth", authRoutes);
app.use("/api/customers", customerRoutes);
app.use("/api/shops", shopRoutes);
app.use("/api/networks", networkRoutes);
app.use("/api/waybill-recharge", waybillRechargeRoutes);
app.use("/api/transactions", transactionRoutes);
app.use("/api/upload", uploadRoutes);
app.use("/api/waybill-stats", waybillStatsRoutes);

// 健康检查
app.get("/api/health", (req, res) => {
  res.json({ status: "OK", message: "服务器运行正常" });
});

// 404 处理
app.use("*", (req, res) => {
  res.status(404).json({ error: "接口不存在" });
});

// 错误处理中间件
app.use((error, req, res, next) => {
  console.error("服务器错误:", error);
  res.status(500).json({ error: "服务器内部错误" });
});

// 启动服务器
async function startServer() {
  try {
    // 连接数据库
    await connectDB();

    // 启动服务器
    app.listen(PORT, () => {
      console.log(`服务器运行在 http://localhost:${PORT}`);
      console.log(`API 文档: http://localhost:${PORT}/api/health`);
    });
  } catch (error) {
    console.error("服务器启动失败:", error);
    process.exit(1);
  }
}

startServer();
